package request

import (
	"fmt"
	"time"
	"zsc-boot/core"

	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type BatchUpdate struct {
	Ids       []uint `json:"ids"`
	UserId    *uint  `json:"userId"`
	IsBlack   *bool  `json:"isBlack" gorm:"column:is_black;comment:是否黑名单用户;default:false"`
	Delete    bool   `json:"delete"`
	ChannelId uint   `json:"channel"`
	Category  string `json:"category" gorm:"size:8;column:category;comment:类型:ABC;default:A"`
	IsNew     *bool  `json:"isNew"`
}

type BatchCollect struct {
	Ids       []uint `json:"ids"`
	IsCollect bool   `json:"isCollect" gorm:"column:is_collect;default:false;comment:是否收藏"`
}

type CustomerUpdate struct {
	ID             uint           `json:"Id" form:"Id" gorm:"column:id;primaryKey;comment:主键ID"` // 主键ID
	UpdateUid      uint           `json:"updateUid" gorm:"column:update_uid;comment:更新人"`        // 更新时间
	City           string         `json:"city" gorm:"column:city;size:32"`
	Name           string         `json:"name" gorm:"column:name;size:128"`
	CompanyName    string         `json:"companyName" gorm:"column:company_name;comment:公司名"`
	RegisterAmount uint           `json:"registerAmount" gorm:"column:register_amount;comment:注册金额"`
	RealAmount     string         `json:"realAmount" gorm:"column:real_amount;comment:实缴金额"`
	Remark         string         `json:"remark" gorm:"column:remark;default:''" `
	Notes          string         `json:"notes" gorm:"column:notes;default:'';comment:点评"`
	Sex            string         `json:"sex" gorm:"column:sex;default:'';size:8"`
	Age            uint8          `json:"age" gorm:"column:age"`
	FollowStatus   string         `json:"followStatus" gorm:"column:follow_status;default:'新线索';comment:跟进状态，新线索，待跟进，空号，停机，有意向，无意向，已加微信，已签约，转商机;size:32"`
	UserId         uint           `json:"userId" gorm:"column:user_id;comment:归属员工id;index:inx_user_id;default:0"`
	ChannelId      uint           `json:"channelId" gorm:"column:channel_id;comment:渠道id"`
	IsBlack        bool           `json:"isBlack" gorm:"column:is_black;comment:是否黑名单用户;default:false"`
	IsCollect      bool           `json:"isCollect" gorm:"column:is_collect;default:false;comment:是否收藏"`
	Tag            datatypes.JSON `json:"tag" gorm:"column:tag;comment:客户标签"`
	Category       string         `json:"category" gorm:"size:8;column:category;comment:类型:ABC;default:A"`
	Level          *uint8         `json:"level" gorm:"column:level;comment:星级;default:1"`
}
type CustomerListReq struct {
	core.PageInfo
	Id                  uint           `json:"Id" form:"Id" gorm:"column:id;primaryKey;comment:主键ID"` // 主键ID
	Name                string         `json:"name" gorm:"column:name;size:128"`
	Mobile              string         `json:"mobile" gorm:"column:mobile;index:inx_mobile;size:32"`
	FollowStatus        string         `json:"followStatus" gorm:"column:follow_status;default:'新线索';comment:跟进状态，新线索，待跟进，空号，停机，有意向，无意向，已加微信，已签约，转商机;size:32"`
	UserId              uint           `json:"userId" gorm:"column:user_id;comment:归属员工id;index:inx_user_id;default:0"`
	DepId               uint           `json:"depId"`
	ChannelId           uint           `json:"channelId"`
	Tag                 map[string]any `json:"tag"`
	NoFollowDay         uint           `json:"noFollowDay"` //未跟进天数
	ImportTimeStart     string         `json:"importTimeStart"`
	ImportTimeEnd       string         `json:"importTimeEnd"`
	AssignedTimeStart   string         `json:"assignedTimeStart"`
	AssignedTimeEnd     string         `json:"assignedTimeEnd"`
	FollowTimeStart     string         `json:"followTimeStart"`
	FollowTimeEnd       string         `json:"followTimeEnd"`
	IsCollect           *bool          `json:"isCollect" gorm:"column:is_collect;default:false;comment:是否收藏"`
	ImportNoFollow      bool           `json:"importNoFollow"`   //从未沟通过
	AssignedNoFollow    bool           `json:"assignedNoFollow"` //分配后未沟通过
	IsNew               *bool          `json:"isNew"`
	LastFollowTimeOrder string         `json:"lastFollowTimeOrder"`
	Category            string         `json:"category"`
	Level               *uint8         `json:"level"`
}

func (req CustomerListReq) BuildWhere(db *gorm.DB) *gorm.DB {
	if req.Id != 0 {
		db.Where("id = ?", req.Id)
	}
	if req.Mobile != "" {
		db.Where("mobile like ?", "%"+req.Mobile+"%")
	}
	if req.IsNew != nil {
		db.Where("is_new = ?", *req.IsNew)
	}
	if req.IsCollect != nil {
		db.Where("is_collect = ?", *req.IsCollect)
	}
	if req.Name != "" {
		db.Where("name like ?", "%"+req.Name+"%")
	}
	if req.FollowStatus != "" {
		db.Where("follow_status = ?", req.FollowStatus)
	}
	if req.ChannelId != 0 {
		db.Where("channel_id = ?", req.ChannelId)
	}
	if len(req.Tag) > 0 {
		for k, v := range req.Tag {
			db.Where(gorm.Expr(fmt.Sprintf("json_extract(tag,'$.%s') = %v", k, v)))
		}
	}
	//未跟进天数
	if req.NoFollowDay != 0 {
		db.Where("? - last_follow_time > ?", time.Now().Unix(), req.NoFollowDay*86400)
	}
	if req.Level != nil {
		db.Where("level = ?", req.Level)
	}

	if req.AssignedTimeStart != "" {
		tmp, _ := time.Parse(time.DateOnly, req.AssignedTimeStart)
		db.Where("assigned_time > ? ", tmp.Unix())
	}
	if req.AssignedTimeEnd != "" {
		tmp, _ := time.Parse(time.DateOnly, req.AssignedTimeEnd)
		db.Where("assigned_time <= ? ", tmp.Unix()+86400-1)
	}
	if req.ImportTimeStart != "" {
		tmp, _ := time.Parse(time.DateOnly, req.ImportTimeStart)
		db.Where("import_time > ? ", tmp.Unix())
	}
	if req.ImportTimeEnd != "" {
		tmp, _ := time.Parse(time.DateOnly, req.ImportTimeEnd)
		db.Where("import_time < ? ", tmp.Unix()+86400-1)
	}

	//分配后未跟进过
	if req.AssignedNoFollow {
		db.Where("last_follow_time <= assigned_time")
	}
	//从未跟进过
	if req.ImportNoFollow {
		db.Where("last_follow_time = assigned_time")
	}
	if req.IsNew != nil {
		db.Where("is_new = ?", *req.IsNew)
	}
	if req.Category != "" {
		db.Where("category = ?", req.Category)
	}
	return db
}

func (req CustomerListReq) Order(db *gorm.DB) *gorm.DB {
	if req.LastFollowTimeOrder != "" {
		if req.LastFollowTimeOrder == "asc" {
			db.Order("last_follow_time asc")
		} else if req.LastFollowTimeOrder == "desc" {
			db.Order("last_follow_time desc")
		}
	} else {
		db.Order("assigned_time desc")
	}
	return db
}

type CustomerListNextReq struct {
	core.PageInfo
	Id                  int            `json:"id"`
	Name                string         `json:"name" gorm:"column:name;size:128"`
	Mobile              string         `json:"mobile" gorm:"column:mobile;index:inx_mobile;size:32"`
	FollowStatus        string         `json:"followStatus" gorm:"column:follow_status;default:'新线索';comment:跟进状态，新线索，待跟进，空号，停机，有意向，无意向，已加微信，已签约，转商机;size:32"`
	UserId              uint           `json:"userId" gorm:"column:user_id;comment:归属员工id;index:inx_user_id;default:0"`
	DepId               uint           `json:"depId"`
	ChannelId           uint           `json:"channelId"`
	Tag                 map[string]any `json:"tag"`
	NoFollowDay         uint           `json:"noFollowDay"` //未跟进天数
	ImportTimeStart     string         `json:"importTimeStart"`
	ImportTimeEnd       string         `json:"importTimeEnd"`
	AssignedTimeStart   string         `json:"assignedTimeStart"`
	AssignedTimeEnd     string         `json:"assignedTimeEnd"`
	FollowTimeStart     string         `json:"followTimeStart"`
	FollowTimeEnd       string         `json:"followTimeEnd"`
	IsCollect           *bool          `json:"isCollect" gorm:"column:is_collect;default:false;comment:是否收藏"`
	ImportNoFollow      bool           `json:"importNoFollow"`   //从未沟通过
	AssignedNoFollow    bool           `json:"assignedNoFollow"` //分配后未沟通过
	IsNew               *bool          `json:"isNew"`
	IsPrevious          bool           `json:"isPrevious"`
	LastFollowTimeOrder string         `json:"lastFollowTimeOrder"`
	Category            string         `json:"category"`
	Level               uint8          `json:"level"`
}

func (req CustomerListNextReq) Order(db *gorm.DB) *gorm.DB {
	if req.LastFollowTimeOrder != "" {
		if req.LastFollowTimeOrder == "asc" {
			db.Order("last_follow_time asc")
		} else if req.LastFollowTimeOrder == "desc" {
			db.Order("last_follow_time desc")
		}
	} else {
		db.Order("created_at desc")
	}
	return db
}

func (req CustomerListNextReq) BuildWhere(db *gorm.DB) *gorm.DB {
	if req.Mobile != "" {
		db.Where("mobile like ?", "%"+req.Mobile+"%")
	}
	if req.IsCollect != nil {
		db.Where("is_collect = ?", *req.IsCollect)
	}
	if req.Name != "" {
		db.Where("name like ?", "%"+req.Name+"%")
	}
	if req.FollowStatus != "" {
		db.Where("follow_status = ?", req.FollowStatus)
	}
	if req.ChannelId != 0 {
		db.Where("channel_id = ?", req.ChannelId)
	}
	if len(req.Tag) > 0 {
		for k, v := range req.Tag {
			db.Where(gorm.Expr(fmt.Sprintf("json_extract(tag,'$.%s') = %v", k, v)))
		}
	}
	//未跟进天数
	if req.NoFollowDay != 0 {
		db.Where("? - last_follow_time > ?", time.Now().Unix(), req.NoFollowDay*86400)
	}

	if req.AssignedTimeStart != "" {
		tmp, _ := time.Parse(time.DateOnly, req.AssignedTimeStart)
		db.Where("assigned_time > ? ", tmp.Unix())
	}
	if req.AssignedTimeEnd != "" {
		tmp, _ := time.Parse(time.DateOnly, req.AssignedTimeEnd)
		db.Where("assigned_time <= ? ", tmp.Unix()+86400-1)
	}
	if req.ImportTimeStart != "" {
		tmp, _ := time.Parse(time.DateOnly, req.ImportTimeStart)
		db.Where("import_time > ? ", tmp.Unix())
	}
	if req.ImportTimeEnd != "" {
		tmp, _ := time.Parse(time.DateOnly, req.ImportTimeEnd)
		db.Where("import_time < ? ", tmp.Unix()+86400-1)
	}

	//分配后未跟进过
	if req.AssignedNoFollow {
		db.Where("last_follow_time <= assigned_time")
	}
	//从未跟进过
	if req.ImportNoFollow {
		db.Where("last_follow_time = assigned_time")
	}
	if req.Category != "" {
		db.Where("category = ?", req.Category)
	}
	if req.Level != 0 {
		db.Where("level = ?", req.Level)
	}
	return db
}
